package structures.compare;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import structures.xmltable.ServiceBaseTypeParameter;
import structures.xmltable.ServiceParameterTable;
import structures.xmltable.ServiceTableColumn;

public class Comparer implements Serializable {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -6759999332463714156L;

	private List<ServiceParameterTable> tableList;
	
	private CompareBagKeyList bagKeys;
	private List<CompareLine> values;
	private List<ServiceTableColumn> columns;
	
	public Comparer() {
		
	}
	
	public void clear(){
		values = new ArrayList<CompareLine>();
		bagKeys = new CompareBagKeyList();
		columns = new ArrayList<ServiceTableColumn>();
		tableList = new ArrayList<ServiceParameterTable>();
	}
	
	public void addToList(ServiceParameterTable table){
		if(bagKeys == null){
			clear();
		}
		tableList.add(table);
	}

	public void compare(){
		for (ServiceParameterTable table : tableList) {
			Integer index = columns.size();
			for (ServiceBaseTypeParameter param : table.getServiceBaseTypeParameters()) {
				if(!bagKeys.contains(param.getBagKey())){
					bagKeys.add(param.getBagKey());
					values.add(new CompareLine());
				}
				values.get(bagKeys.getIndex(param.getBagKey()))
					.addCell(param.getValue(), index);
			}
			columns.add(new ServiceTableColumn(null, columns.size() + " - " + table.getVisualServiceName(30), columns.size() + 1));
		}
		synchronize();
	}
	
	public void synchronize(){
		Integer colIndex = columns.size() - 1;
		for (CompareLine line : values) {
			while(line.getCells().size() < colIndex + 1){
				line.getCells().add(new CompareCell("<<Not Returned>>"));
				line.setHasNotReturnedValues(true);
				line.setHasDifferentValues(false);
			}
		}
		int i = 0;
		for (CompareLine line : values) {
			line.getCells().add(0, new CompareCell(bagKeys.get(i)));
			i++;
		}
		columns.add(0, new ServiceTableColumn(null, "Bagkeys", 0));
	}

	public CompareBagKeyList getBagKeys() {
		return bagKeys;
	}

	public void setBagKeys(CompareBagKeyList bagKeys) {
		this.bagKeys = bagKeys;
	}

	public List<CompareLine> getValues() {
		return values;
	}

	public void setValues(List<CompareLine> values) {
		this.values = values;
	}

	public List<ServiceTableColumn> getColumns() {
		return columns;
	}

	public void setColumns(List<ServiceTableColumn> columns) {
		this.columns = columns;
	}
	public int getColumnCount(){
		int count = 0;
		if(columns != null){
			count = columns.size();
		}
		return count;
	}
	
}
